package Impl;

import com.ny.entity.Student;
import until.SqlConnection;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StudentDaoImpl implements StudentDao {


    Connection connection = SqlConnection.getCon();

    public StudentDaoImpl() throws SQLException {
    }


    public int add(Student student) throws SQLException {
        String sql = "insert into students(name,password,phone) values(?,?,?)";

        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setString(1, student.getStudentName());
        preparedStatement.setString(2, student.getStudentPassword());
        preparedStatement.setString(3, student.getStudentPhone());
        return preparedStatement.executeUpdate();


    }

    @Override
     public Student login(String studentName, String studentPassword) throws SQLException {
        String sql = "select * from students where name = ? and password = ?";
//         3.执行SQL语句
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        // 给问号赋值
        preparedStatement.setString(1,studentName);
        preparedStatement.setString(2,studentPassword);
        ResultSet resultSet = preparedStatement.executeQuery();
//              把 resultSet 中的数据先拿出来：resultSet.getInt("列名")
//               把值拿出来之后交给student对象。student.setStudentId(resultSet.getInt("id"));
        //   4.处理结果:把数据交给student对象.resultSet.getInt("列名")：获取到列名值
        //   student.setStudentId：给学生student的id属性赋值
        if (resultSet.next()){
            Student student = new Student();
            student.setStudentId(resultSet.getInt("student_id"));
            student.setStudentName(resultSet.getString("name"));
            student.setStudentPhone(resultSet.getString("phone"));
            student.setStudentPassword(resultSet.getString("password"));
            return student;
        }
        return null;
    }

    }

